<template>
	<view class="content">
		<!-- 状态栏占位符h5 -->
		<view class="status_bar"></view>

		<!-- #ifdef MP -->
		<!-- 微信小程序胶囊区域占位 -->
		<view class="" :style="{'height':navibarHeight+'px'}" />
		<!-- #endif -->


		<view class="third-bg-color fixed z-16" style="width: 100%;">
			
			<view class="h-80r pl-20r pr-20r box-shadow flex items-center justify-between" style="background-color: #fff;">
				<view @click="goBack" class="third-bg-color w-70r h-70r text-center rounded-35r"
					style="box-shadow: 2px 2px 6px 0px #A8A8A8;">
					<text class="text-40r iconfont icon-zuojiantou"></text>
				</view>
				<view class="text-center">
					<text class="text-30r">{{curCategory}}</text>
				</view>
				<view @click="savePic"
					class="flex flex-center items-center second-bg-color w-120r h-50r rounded-30r box-shadow"
					style="color: #fff;">
					<text class="text-20r">保存</text>
				</view>
			
			</view>
			
			
			<view class="m-10r mt-20r">
				<wy-canvas ref="canvas" @textSelect="selectText" :bgImage="bgImage" :mode="mode" :graph="graph">
				</wy-canvas>
			</view>


			<view class="flex justify-around pt-10r pb-10r">
				<view @click="clickItem(0)" :class="curIndex == 0?'inset-shadow':'box-shadow'"
					class="flex flex-col flex-center w-150r h-150r rounded-30r third-bg-color">
					<text class="text-80r mb-5r text-main iconfont icon-yifu"></text>
					<text class="text-30r main-color" :class="curIndex == 0?'second-color':''">版型</text>
				</view>
				<view @click="clickItem(1)" :class="curIndex == 1?'inset-shadow':'box-shadow'"
					class="flex flex-col flex-center w-150r h-150r rounded-30r third-bg-color">
					<text class="text-80r mb-5r text-main iconfont icon-tupian"></text>
					<text class="text-30r main-color" :class="curIndex == 1?'second-color':''">图案</text>
				</view>
				<view @click="clickItem(2)" :class="curIndex == 2?'inset-shadow':'box-shadow'"
					class="flex flex-col flex-center w-150r h-150r rounded-30r third-bg-color">
					<text class="text-80r mb-5r text-main iconfont icon-wenzixiaoguo"></text>
					<text class="text-30r main-color" :class="curIndex == 2?'second-color':''">文字</text>
				</view>

			</view>

		</view>
		<!-- 占位 -->
		<view style="height: 1020rpx;"></view>



		<!-- <fui-button @click="addGraph" :margin="['10rpx','20rpx']" text="添加图案"></fui-button> -->
		<!-- <fui-button @click="addText" :margin="['10rpx','20rpx']" text="添加文字"></fui-button> -->
		<!-- <fui-button @click="loadFont" :margin="['10rpx','20rpx']" text="加载字体" ></fui-button> -->
		<!-- <fui-button @click="changeMode" :margin="['10rpx','20rpx']" text="画笔"></fui-button> -->
		<!-- <fui-button @click="rePaintLine" :margin="['10rpx','20rpx']" text="重绘线段"></fui-button> -->
		<!-- <text >字体</text> -->

		<view class="">

			<view class="third-bg-color pl-20r pr-20r pb-20r" :class="{'hidden':curIndex != 0}">
				<text class="text-main text-30r">颜色</text>
				<scroll-view class="whitespace-nowrap" style="width: 100%;" scroll-x="true" enable-flex>
					<view @click="changeColor(index)" v-for="(item,index) in colors" :key="index"
						:class="curColorIndex == index?'inset-shadow':'box-shadow'"
						class="box-shadow rounded-20r ml-10r mr-10r inline-block w-200r h-100r"
						:style="{'background-color':item}"></view>
				</scroll-view>
				<text class="block text-main text-30r">类型</text>
				<view @click="changeCategory(index)" v-for="(item,index) in data" :key="index"
					:class="curCategoryIndex == index?'inset-shadow':'box-shadow'"
					class="text-40r main-color box-shadow rounded-20r pl-20r pr-20r ml-10r mr-10r inline-block">
					{{item._id}}
				</view>

			</view>
			<!-- 图片素材区 开始-->
			<view class="third-bg-color" :class="{'hidden':curIndex != 1}" style="width: 100%;">
				<scroll-view scroll-y="true" class="scroll-Y" :style="{'height':scroll_height+'rpx'}" @scroll="scroll">
					<view class="flex flex-wrap pl-30r pr-30r">
						<view @click="addMypic"
							class="w-150r h-150r box-shadow text-center rounded-10r m-10r third-bg-color">
							<text class="text-light iconfont icon-21"
								style="font-size: 100rpx;line-height: 150rpx;"></text>
						</view>
						<view @click="addPic(item.img)" v-for="(item,index) in parttens" :key="index"
							class="flex flex-center w-150r h-150r box-shadow  rounded-10r m-10r ">
							<image class="w-140r h-140r" :src="item.img" style="" mode="aspectFit"></image>
						</view>

					</view>

				</scroll-view>

			</view>
			<!-- 图片素材区 结束-->


			<view class=" h-200r" :class="{'hidden':curIndex != 2}" style="width: 100%;">
				<fui-input v-model="text" clearable placeholder="输入想要添加的文字吧" maxlength="20" inputBorder trim
					:backgroundColor="this.theme.thirdColor">
					<view @click="addText"
						class="ml-40r text-20r third-color text-center box-shadow leading-50r main-bg-color w-100r h-50r rounded-50r">
						添加</view>
				</fui-input>
				<t-color-picker ref="colorPicker" :color="defaultColor" @confirm='comfirmColor'></t-color-picker>

				<!-- <fui-button text="默认按钮" @click="popSelector"></fui-button> -->
				<view @click="popSelector" class="mt-10r flex flex-center w-150r rounded-50r h-50r box-shadow">
					<text class="text-20r">切换颜色</text>
					<view class="h-40r w-40r rounded-20r" :style="{'background-color': this.textColor}"></view>
				</view>

			</view>

			<!-- 弹出对话框 -->
			<fui-dialog :show="dialogVisible" title="保存设计" :buttons="buttons" maskClosable @click="clickDialog"
				@close="closeDialog">
				
				
				<view class="flex flex-col flex-center">
					<view class="w-330r mb-20r">
						<uni-easyinput  confirmType="send" :styles="styles" clearable :maxlength="10" v-model="designName" placeholder="给作品起个名字吧(1~10字)">
						</uni-easyinput>
					</view>
					<view class="flex flex-center">
						<text @click="this.selected = !this.selected" class="text-60r iconfont "
							:class="[selected ? 'icon-duigouzhong main-color':'icon-duigou-weigouxuan']"></text>
						<text class="leading-30r text-30r">是否同步到个人动态</text>
					</view>
				</view>
				

			</fui-dialog>

		</view>


	</view>
</template>

<script>
	import tColorPicker from '@/components/t-color-picker/t-color-picker.vue'
	export default {
		components: {
			tColorPicker
		},
		data() {
			return {
				graph: {},
				mode: 'graph',
				curIndex: 0,
				navibarHeight: 0,
				colors: [],
				curColorIndex: 0,
				curCategoryIndex: 0,
				curCategory: "",
				data: {},
				designName:"",
				clothImg: "",
				curTemplateCloth: {},
				bgImage: "",
				styles: {
					color: '#FF5632',
					borderColor: '#E5E5E5'
				},
				curColor: "",
				scroll_height: 0,
				parttens: [],
				text: '',
				textIndex: 0,
				textColor: 'red',
				display: false,
				noSelect: true,
				defaultColor: {
					r: 255,
					g: 0,
					b: 0,
					a: 1
				},
				dialogVisible: false,
				selected: true,
				buttons: [{
						text: '确定',
						color: this.theme.mainColor
					},
					{
						text: '取消',
						color: this.theme.mainColor
					}
				],
				clothWork: {
					cloth_imgs: [],
					template_id: '',
					name : ''
				}
			};
		},

		onLoad() {
			// #ifdef MP
			uni.getSystemInfo({
				success: (r) => {
					let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
					let statusBarHeight = r.statusBarHeight;
					this.navibarHeight = menuButtonInfo.height;
				}
			})
			// #endif

			var windowWidth = uni.getSystemInfoSync().windowWidth;
			var windowHeight = uni.getSystemInfoSync().windowHeight;
			//rpx与px单位之间的换算 : 750/windowWidth = 屏幕的高度（rpx）/windowHeight
			this.scroll_height = 750 * windowHeight / windowWidth - 1020;
			console.log(this.scroll_height);
			vk.callFunction({
				url: 'client/clothes/pub/getParttens'
			}).then((r) => {
				this.parttens = r.data;
				// console.log(this.parttens);
			});


			vk.callFunction({
				url: 'client/clothes/pub/getClothTemplates',
				title: '加载中...'
			}).then((r) => {
				this.data = r.data;
				this.colors = this.data[0].colors;
				this.curCategory = this.data[0]._id;
				this.curColor = this.colors[0];
				// console.log(this.data);
				this.requestTempImgs(this.curColor, this.curCategory);
			});


		},
		methods: {
			scroll() {

			},
			clickItem(i) {
				this.curIndex = i;
			},
			changeItem(e) {
				this.curIndex = e.detail.current;
			},
			changeColor(i) {
				this.curColorIndex = i;
				this.curColor = this.colors[i];
				this.requestTempImgs(this.curColor, this.curCategory);
			},
			changeCategory(i) {
				this.curCategoryIndex = i;
				this.curCategory = this.data[i]._id;
				this.colors = this.data[i].colors;
				this.curColor = this.colors[0];
				this.requestTempImgs(this.curColor, this.curCategory);
			},
			goBack() {
				uni.navigateBack()
			},
			comfirmColor(e) {
				// console.log('change color to:'+this.textColor);
				this.textColor = `rgba(${e.rgba.r},${e.rgba.g},${e.rgba.b},${e.rgba.a})`;
				const curText = this.$refs.canvas.drawArr[this.textIndex];
				if (curText && curText.selected) {
					this.$refs.canvas.drawArr[this.textIndex].color = this.textColor;
					this.$refs.canvas.draw();
				}

			},
			selectText(idx) {
				console.log("text index selected");
				this.textIndex = idx;
				this.noSelect = false;
			},
			requestTempImgs(color, name) {
				vk.callFunction({
					url: 'client/clothes/pub/getClothTempImg',
					title: '请求中...',
					data: {
						color: color,
						name: name
					},
				}).then((r) => {
					let that = this;
					this.curTemplateCloth = r.data;
					uni.getImageInfo({
						src: r.data.cloth_imgs[0],
						success: function(image) {
							that.bgImage = image.path;
							// uni.setStorage({
							// 	key: 'cloth_template_img',
							// 	data: image.path,
							// 	success() {
							// 		// that.bgImage = uni.getStorageSync('cloth_template_img');
							// 		// that.$refs.canvas.draw();
							// 		// console.log(that.bgImage);
							// 	}
							// });
						}
					});
				});
			},
			addPic(img) {
				uni.downloadFile({
					url: img,
					success: (res) => {
						this.graph = {
							w: 100,
							h: 100,
							type: 'image',
							url: res.tempFilePath
						}
					}
				});


			},
			addMypic() {
				var height = 0;
				var width = 0;
				let that = this;
				uni.chooseImage({
					success: (res) => {
						uni.getImageInfo({
							src: res.tempFilePaths[0],
							success(image) {
								console.log("图片大小：", image.height, "*", image.width);
								height = image.height;
								width = image.width;
								console.log(height, width);
								if (height <= 60 || width <= 60) {
									height *= 2;
									width *= 2;
								}
								if (height >= 1000 || width >= 1000) {
									height /= 10;
									width /= 10;
								}
								if (height >= 200 || width >= 200) {
									height /= 2;
									width /= 2;
								}
								that.graph = {
									w: width,
									h: height,
									type: 'image',
									url: res.tempFilePaths[0]
								}

							}
						})
					}
				})

			},
			// 测试添加图案
			// addGraph() {
			// 	this.graph = {
			// 		w: 100,
			// 		h: 100,
			// 		type: 'image',
			// 		url: '../../static/logo.png'
			// 	}
			// },
			popSelector() {
				this.$refs.colorPicker.open();
			},
			addText() {

				if (this.stringUtils.isBlank(this.text)) {
					vk.toast("请输入要添加的文字");
					return;
				}
				const randomX = 40 + Math.floor(Math.random() * 50);
				const randomY = 100 + Math.floor(Math.random() * 50);
				this.graph = {
					x: randomX,
					y: randomY,
					fontSize: 60,
					color: this.textColor,
					type: 'text',
					text: this.text
				}
			},
			clickDialog(e) {
				console.log(e.index);
				if (this.buttons[e.index].text == '取消') {
					this.dialogVisible = false;
					return;
				}
				if (this.buttons[e.index].text == '确定') {
					if(this.designName == ''){
						vk.toast('作品名不能为空');
						return;
					}
					vk.showLoading('保存中...');
					this.$refs.canvas.export()
						.then((filePath) => {
							let that = this;
							uniCloud.uploadFile({
								filePath: filePath,
								cloudPath: `${Date.now()}${this.curTemplateCloth.name}${this.curTemplateCloth._id}.png`,
								onUploadProgress: function(progressEvent) {
									console.log(progressEvent);
									var percentCompleted = Math.round(
										(progressEvent.loaded * 100) / progressEvent.total
									);
								},
								success(r) {
									console.log(r);

									that.clothWork.cloth_imgs[0] = r.fileID;
									that.clothWork.template_id = that.curTemplateCloth._id;
									that.clothWork.name = that.designName;
									vk.callFunction({
										url: 'client/clothes/kh/addClothWork',
										data: that.clothWork,
										success: (data) => {
											if (that.selected) {
												vk.callFunction({
													url: 'client/dynamic/kh/publishDynamic',
													data: {
														content: '我设计了一件衣服，大家快来看看吧~',
														dynamic_banner_imgs:that.clothWork.cloth_imgs,
														hasWork:true,
														work_id:data.id,
														dynamic_status:1
													},
													success: (data) => {
														vk.navigateToHome();
													}
												});
											}
										}
									});
								},
								fail() {
									vk.toast("保存失败");
								},
								complete() {

								}
							});
							console.log(filePath);


						})
						.catch((e) => {
							console.error(e);
							vk.toast("保存失败");
						})
						.finally(() => {
							this.dialogVisible = false;
							vk.hideLoading();

						})

				}
			},
			closeDialog() {
				this.dialogVisible = false;
			},
			savePic() {
				this.dialogVisible = true;

				// this.$refs.canvas.export()
				// 	.then((filePath) => {
				// 		console.log(filePath);
				// 		uni.previewImage({
				// 			urls: [filePath]
				// 		})
				// 	})
				// 	.catch((e) => {
				// 		console.error(e);
				// 	})
			},
			loadFont() {
				const url = 'https://at.alicdn.com/wf/webfont/xMREYHRGVsNu/ExBsoeSDtVCkDepRUn_WA.woff2';
				uni.loadFontFace({
					family: 'fonttest',
					source: `url("${url}")`,
					success: () => {
						console.log('success');
					}
				})
			},
			changeMode() {
				this.mode = this.mode == 'graph' ? 'line' : 'graph';
				console.log('目前模式：' + this.mode);
			},
			rePaintLine() {
				this.$refs.canvas.rePaintLine();
			}
		}
	}
</script>

<style lang="scss">
	.content {
		font-family: 'fonttest';
		font-size: 50rpx;
		// font-weight: bold;
	}

	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
	}


</style>
